#!/usr/bin/python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
import sys
import datetime
import time
import pytz

def mail(to, subject, text, account_name, account_pwd, attachmentPath, source_email):
	msg = MIMEMultipart()

	if subject == 'no subject': subject = ''

	#msg['From'] = 'kathia@wulicious.com'
	msg['From'] = source_email
	msg['To'] = to
	msg['Subject'] = subject
	msg.attach(MIMEText(text))

	if attachmentPath != '' and attachmentPath != 'none': attachList = [attachmentPath]
	else: attachList = []
	for each in attachList:
		part = MIMEBase('application', 'octet-stream')
		part.set_payload(open(each , 'rb').read())
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition',
				  'attachment; filename="%s"' % os.path.basename(each))
		msg.attach(part)


	mailServer = smtplib.SMTP_SSL()
	mailServer.connect('smtp.webfaction.com')

	mailServer.login(account_name, account_pwd)
	mailServer.sendmail('info@wulicious.com', to, msg.as_string())
	mailServer.close()

	#if os.path.exists(attachmentPath): os.remove(attachmentPath)
	

def getTimeInfo():
	currentTime = datetime.datetime.now(pytz.timezone('US/Eastern'))
	dateStuff =  str(currentTime.month) + '/' + str(currentTime.day) + '/' + str(currentTime.year)

	hour1 = str(currentTime.hour)
	min1 = str(currentTime.minute)
	if len(hour1) == 1: hour1 = '0' + hour1
	if len(min1) == 1: min1 = '0' + min1

	hourStrin = hour1 + ':' + min1

	return dateStuff + ' , ' + hourStrin

	
def reset_log():
	log_length = 500
	if not os.path.exists('./fax_log.txt'): return

	fin = open('fax_log.txt','r')
	lns = fin.readlines()
	fin.close()

	if len(lns) > log_length:
		start_p = len(lns) - log_length
		fin = open('fax_log.txt','w')
		for m in range(start_p, len(lns)):
			fin.write(lns[m])
		fin.close()



if __name__ == "__main__":
	destinationEmail = sys.argv[1].strip()
	subject = sys.argv[2].strip()
	fileName = sys.argv[3].strip()
	account_name = sys.argv[4].strip()
	account_pswd = sys.argv[5].strip()
	sourceEmail = sys.argv[6].strip()

	try: attachmentPath = sys.argv[7].strip()
	except: attachmentPath = ''

	prepend = 'src/tmpMailMsg/'
	#prepend = './tmpMailMsg/'

	subject = subject.replace('kathia', ' ')
	if not os.path.exists(prepend + fileName): 
		print(prepend + fileName + ' does not exist.')
		print sys.argv
		print('\n\n')
		sys.exit()

	fin = open(prepend + fileName,'r')
	msg = fin.read()
	fin.close()

	to_email_list = destinationEmail.split(',')
	for m in to_email_list:
		mail(m, subject, msg, account_name, account_pswd, attachmentPath, sourceEmail)

	os.remove(prepend + fileName)


